package com.suncaper.han_yi_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suncaper.han_yi_system.exception.CustomerException;
import com.suncaper.han_yi_system.mapper.ApplicationMapper;
import com.suncaper.han_yi_system.mapper.BatchMapper;
import com.suncaper.han_yi_system.mapper.RegistrationMapper;
import com.suncaper.han_yi_system.pojo.entity.*;
import com.suncaper.han_yi_system.pojo.vo.RegistrationVo;
import com.suncaper.han_yi_system.service.RegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RegistrationServiceImpl extends ServiceImpl<RegistrationMapper, Registration> implements RegistrationService {

    @Autowired
    ApplicationMapper applicationMapper;

    @Autowired
    BatchMapper batchMapper;

    @Autowired
    StudentServiceImpl studentServiceImpl;

    @Override
    public int updateByStudent(Registration registration) {

        registration.setUpdateTime(LocalDateTime.now());

        return getBaseMapper().updateByStudent(registration);
    }

    @Override
    public void saveRegistration(Registration registration) {
        Application application = applicationMapper.selectOne(new QueryWrapper<Application>()
                .eq("id", registration.getApplicationId()));

        Batch batch = batchMapper.selectOne(new QueryWrapper<Batch>()
                .eq("id", application.getBatchId()));

        if(batch.getRegisterDeadline().isBefore(LocalDateTime.now()))
            throw new CustomerException("登记时间已截止");

        Long n1 = getBaseMapper().selectCount(new QueryWrapper<Registration>()
                .eq("application_id", registration.getApplicationId()));
        if(n1 > 0) throw new CustomerException("已登记过，请勿重复登记");

        if(getBaseMapper().insert(registration) == 0)
            throw new CustomerException("申请还未通过，无法登记");

    }

    @Override
    public List<RegistrationVo> findByUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        return getBaseMapper().findByUserId(userId);
    }
}